using Manager;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class ExperienceBar : MonoBehaviour
{
    private GameObject _bar;
    private Text _levelText;
    public static ExperienceBar Instance;
    private float experienceAmount = 0f;
    private float buffTime = 1f;//经验增加的缓冲时间
    private Coroutine _bufferCoroutine; // 保存协程引用，用于取消

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(this);
        }
        else
            Instance = this;
    }
    
    private void Start()
    {
        _bar = transform.Find("Bar").gameObject;
        _levelText = transform.Find("Level").GetComponent<Text>();
        experienceAmount = 0;
        UpdateExperience();

        //订阅enemyNum为0的事件
        GameManager.Instance.OnEnemyNumIsZero += UpdateExperience;
    }

    private void OnDisable()
    {
        GameManager.Instance.OnEnemyNumIsZero -= UpdateExperience;
    }


    /// <summary>
    /// 更新经验值的UI
    /// </summary>
    public void UpdateExperience()
    {
        // 取消已有的协程（如果存在）
        if (_bufferCoroutine != null)
        {
            StopCoroutine(_bufferCoroutine);
        }

        // 启动新的缓冲效果
        _bufferCoroutine = StartCoroutine(UpdateExper());
    }

    IEnumerator UpdateExper()
    {
        float elapsedTime = 0;
        float oldExperience = _bar.GetComponent<Image>().fillAmount;
        float targetExperience = experienceAmount;
        float remainingExperience = targetExperience; // 跟踪剩余需要填充的经验
        
        // 如果目标经验值超过1，需要处理多次升级的情况
        while (elapsedTime < buffTime && remainingExperience > 0)
        {
            elapsedTime += Time.deltaTime;
            float newFillAmount = Mathf.Lerp(oldExperience, oldExperience + remainingExperience, elapsedTime / buffTime);
            
            // 检查是否需要升级(经验条满了)
            if (newFillAmount >= 1)
            {
                // 升级角色
                Player.Player.instance.LevelUp();
                
                // 更新等级文本
                _levelText.text = "Lv." + Player.Player.instance.currentLevel;
                
                // 计算溢出的经验值
                float overflowExperience = newFillAmount - 1f;
                
                // 重置经验条，设置为溢出的经验值
                _bar.GetComponent<Image>().fillAmount = overflowExperience;
                
                // 更新剩余经验和当前值
                remainingExperience = remainingExperience - (1f - oldExperience);
                oldExperience = overflowExperience;
                elapsedTime = 0; // 重置计时器
            }
            else
            {
                // 正常更新经验条
                _bar.GetComponent<Image>().fillAmount = newFillAmount;
                
                // 如果已经达到这一段的目标值，结束循环
                if (Mathf.Abs(newFillAmount - (oldExperience + remainingExperience)) < 0.01f)
                {
                    remainingExperience = 0;
                }
            }
            
            yield return null;
        }
        
        // 确保最终等级文本是正确的
        _levelText.text = "Lv." + Player.Player.instance.currentLevel;
    }

    /// <summary>
    /// 更新经验值
    /// </summary>
    /// <param name="experience"></param>
    public void UpdateExperienceAmount(float experience)
    {
        experienceAmount = experience;
    }    

    private void OnDestroy()
    {
        if (_bufferCoroutine != null)
        {
            StopCoroutine(_bufferCoroutine);
        }
    }
}
